/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Tiong Jia Ming
 */
public class DBConnectionJm {

    PreparedStatement stmt = null;
    Connection conn = null;
    ResultSet rs = null;
    String update = "", query = "";
    String[] attributes = null;

    public DBConnectionJm() {
        try {
            Class c = Class.forName("com.mysql.jdbc.Driver");
            c.newInstance();
        } catch (Exception e) {
            System.out.println("Error occurred " + e);
        }
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/oasis", "root", "root");
        } catch (SQLException e) {
            System.out.println("Error occurred " + e);
        }
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public ResultSet doQuery() {
        try {
            stmt = conn.prepareStatement(query);
            if (this.attributes == null || this.attributes.length == 0) {
                rs = stmt.executeQuery();
            } else {
                for (int i = 0; i < this.attributes.length; i++) {
                    stmt.setString(i + 1, this.attributes[i]);
                }
            }
            rs = stmt.executeQuery();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.print(query);
        }
        return rs;
    }

    public void setUpdate(String update) {
        this.update = update;
    }

    public boolean doUpdate() {
        boolean updated = false;
        try {
            stmt = conn.prepareStatement(update);
            for (int i = 0; i < this.attributes.length; i++) {
                stmt.setString(i + 1, this.attributes[i]);
            }
            updated = stmt.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return updated;
    }

    public void doClose() {
        try {
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setAttributes(String[] attributes) {
        this.attributes = new String[attributes.length];
        for (int i = 0; i < attributes.length; i++) {
            this.attributes[i] = attributes[i];
        }
    }

    public int getSize() {
        int size = 0;
        try {
            rs.beforeFirst();
            rs.last();
            size = rs.getRow();
        } catch (SQLException e) {
            System.out.println("No Result Set");
        }
        return size;
    }
}
